package com.liqi.frame.comm.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by liqi on 2017/8/17.
 */
public class MapUtil {

    /**
     * 把map对象中的key,value转成字符串 "key1 block1 value1 block2 key2 block1 value2"
     * @param map
     * @param block1
     * @param block2
     * @return
     */
    public static StringBuffer buildToString(Map map, String block1, String block2) {
        StringBuffer sb = new StringBuffer();
        Iterator names = map.keySet().iterator();
        while(names.hasNext()) {
            String name = (String)names.next();
            if(name != null) {
                if (!"".equals(sb.toString())) {
                    sb.append(block2);
                }
                sb.append(name);
                sb.append(block1);
                Object value = map.get(name);
                if(value == null) {
                    sb.append("<NULL>");
                } else if(value instanceof String) {
                    sb.append((String)value);
                } else if(!(value instanceof String[])) {
                    sb.append(value.toString());
                } else {
                    String[] delim = (String[])value;
                    sb.append(delim[0]);
//                    sb.append('[');
//                    for(int propName = 0; propName < delim.length; ++propName) {
//                        if(propName > 0) {
//                            sb.append(',');
//                        }
//                        sb.append(delim[propName]);
//                    }
//                    sb.append(']');
                }
            }
        }
        return sb;
    }

    public static Map<String, Object> toMap(Map<String, String[]> map) {
        Map<String, Object> resultMap = new HashMap<String, Object>(map.size());
        int len;
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            len = entry.getValue().length;
            if (len == 1) {
                resultMap.put(entry.getKey(), entry.getValue()[0]);
            } else if (len > 1) {
                resultMap.put(entry.getKey(), entry.getValue());
            }
        }
        return resultMap;
    }
}
